#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

typedef struct sinhvien
{
        char ten[30];
        float toan;
        float tin;
        float tb;        
};

sinhvien *p;

// nhap danh sach sinh vien
sinhvien *nhapds(int n)
{
     int i;
     p=(sinhvien*)malloc(n*sizeof(sinhvien));
     if(p== NULL)
     {
           printf("\n Loi cap phat bo nho !");
           getch();
           exit(0);      
     }
     else
     {
        for(i = 0; i < n; i++)
        {
          printf("\n-->sinh vien thu %d ",i);
          printf("\n Nhap ho va ten la:");
          fflush(stdin);
          scanf("%s",(p+i)->ten);
          float t = 0;
          printf("\n Diem Toan :");
          scanf("%f",&t);
          (p+i)->toan = t;
          printf("\n Diem Tin :");
          scanf("%f",&t);
          (p+i)->tin =t;
          (p+i)->tb=((p+i)->toan + (p+i)->tin)/2;
          //printf("\n Diem trung binh : %f ",(p+i)->tb);
          
          printf("\n\n");
        }    
     }
     return (0);
}
//in danh sach sinh vien
void inds(sinhvien *p, int n)
{
     int i;
     for(i = 0; i < n; i++)
     {
           puts("\n");
          printf("\nTen:%s",(p+i)->ten);
          printf("\nToan:%6.2f",(p+i)->toan);
          printf("\nTin:%6.2f",(p+i)->tin);
          printf("\nTrungBinh:%6.2f",(p+i)->tb);
     }
}

void swap(sinhvien *sv1,sinhvien *sv2)
{
sinhvien temp;
memcpy(&temp,sv1,sizeof(sinhvien));// ham memcpy co tac dung hoan doi toan struct 
memcpy(sv1,sv2,sizeof(sinhvien));
memcpy(sv2,&temp,sizeof(sinhvien));
}

void sapxep(sinhvien *p, int n)
{
     int i,j,temp;
     // ham tinh diem trung binh
     for(i = 0; i < n; i++)
     {
          (p+i)->tb =((p+i)->toan + (p+i)->tin)/2;
          
     }
     // ham sap xep
     for(i = 0; i < n; i++)
     {
        for(j = i+1; j < n; j++)
        {
           if((p+i)->tb < (p+j)->tb)
           {
              swap((p+i),(p+j));
           }
        }
     }
}

int main(int argc, char *argv[])
{
    int n,i;
    //n=atoi(argv[1]);
    printf("\n nhap n =");
    scanf("%d",&n);
    nhapds(n);
    sapxep(p,n);
    puts("\n Ket qua theo thu tu diem trung binh giam dan la:");
    inds(p,n);
    getch();
    return(0);
}
